# 该文件为更改文件名称，并将新名称的文件复制到另一个文件中
# 关键在于shutil库的使用

import os
import shutil

def creatcopypath(file):
    if not os.path.exists(file):
        os.mkdir(file)
        return file + '/'
    else:
        return file + '/'
if __name__ == '__main__':
    path_loc = '/Users/jiangce/Desktop/车型识别/VOCdevkit/'#根路径

    #创建复制之后的文件夹
    path_imgcopy = path_loc + 'img'
    path_imgcopy = creatcopypath(path_imgcopy)
    path_xmlcopy = path_loc + 'xml'
    path_xmlcopy = creatcopypath(path_xmlcopy)

    VOC = 'VOC0'
    VOCnum = 1
    while (VOCnum < 8):
        if VOCnum == 5:
            VOCnum = 6
        print("VOCnum: {}".format(VOCnum))
        Newname = '0' + str(VOCnum) + '_'
        path_VOC = path_loc+VOC+str(VOCnum)+'/'
        path_xml = path_VOC + 'Annotations/'
        path_img = path_VOC + 'JPEGImages/'
        list_img = os.listdir(path_img)#存储图片文件
        list_xml = os.listdir(path_xml)#存储xml文件
        num_img = 1
        for item_img in list_img:
            print("imgnum: {}".format(num_img))
            name_img = item_img.split('.')[0]#读取文件的名称
            path_imgcopyName = path_img + item_img
            shutil.copyfile(path_imgcopyName, path_imgcopy + Newname+str(num_img) +'.jpg')#复制
            for item_xml in list_xml:
                name_xml = item_xml.split('.')[0]
                if name_img == name_xml:
                    path_xmlcopyName = path_xml + item_xml
                    shutil.copyfile(path_xmlcopyName, path_xmlcopy + Newname + str(num_img) + '.xml')
            num_img = num_img + 1
        VOCnum = VOCnum + 1